/**
 * Copyright (c) 2010 Axa Holding Belgium, SA. All rights reserved.
 * This software is the confidential and proprietary information of the AXA Group.
 */
package chabernac.proxyserver;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.List;

import org.apache.log4j.Logger;

import chabernac.tools.HeaderTools;

public class SocketFactory {
  private static Logger LOGGER = Logger.getLogger( SocketFactory.class );
  
  private String myHost = null;
  private int myPort;
  private boolean isProxyReachable = true;
  private InetAddress myLocalHost = null;
  
  public SocketFactory(String aHost, int aPort) throws UnknownHostException{
    myHost = aHost;
    myPort = aPort;
    myLocalHost = InetAddress.getLocalHost();
  }
  public PSocket createProxySocket() throws UnknownHostException, IOException{
    PSocket theSocket = new PSocket(true);
    theSocket.setSoTimeout( 3000 );
    theSocket.connect( new InetSocketAddress(myHost, myPort) );
    return theSocket;
  }
  
  public PSocket createSocket(List<String> aHeaders) throws UnknownHostException, IOException{
    String[] theHead = aHeaders.get( 0 ).split( " " );
    //get the first line from the headers and open a socket to the web server
    
    
    String theURL = theHead[1];
    
    int thePort = 80;
    String theHost = theURL;
    
    if(theHead[0].equalsIgnoreCase( "CONNECT" )){
      String[] theHostPort = theURL.split( ":" );
      theHost = theHostPort[0];
      thePort = Integer.parseInt( theHostPort[1] );
    } else {
      //second line of headers is 'Host:' in case of GET, POST, ... ?
      //e.g. Host: www.google.be can also contain ':' e.g. Host: x22p0212:8080
      String[] theHostLine = HeaderTools.findHeader( aHeaders, "Host" ).split( ":" );
      theHost = theHostLine[0];
      if(theHostLine.length > 1){
        thePort = Integer.parseInt(theHostLine[1]);
      }
    }
    
    if(isProxyReachable && isProxyNeededForHost(theHost)){
      try {
        return createProxySocket();
      } catch ( Exception e ) {
        isProxyReachable = false;
      }
    }
    
    LOGGER.debug( "Opening socket to  '" + theHost + ":" + thePort +  "'");
    return new PSocket(theHost, thePort, false);
  }
  
  
  
  private boolean isProxyNeededForHost( String anHost ){
    //TODO why do the sockets to the local jboss not work
    if(true) return true;
    try{
      String theIPAddress = InetAddress.getByName( anHost ).getHostAddress();
      if(theIPAddress.startsWith( "10." )) return false;
      if(theIPAddress.startsWith( "192.168." )) return false;
    }catch(UnknownHostException e){
      return true;
    }
    return true;
        
  }
  
  public boolean isProxyReachable(){
    return isProxyReachable;
  }
}
